package top.infopub.mgr.cap.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.dto.cap.ContractPledgeDto;
import top.infopub.enums.cap.CapProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.cap.dao.ContractGuarantyDao;
import top.infopub.mgr.cap.dao.ContractPledgeDao;
import top.infopub.mgr.cap.dao.ContractPledgeDetailDao;
import top.infopub.mgr.cap.domain.ContractPledgeDomain;
import top.infopub.mgr.cap.jsonvo.ContractPledgeJsonVo;
import top.infopub.mgr.cap.service.CapProcessManageService;
import top.infopub.mgr.cap.service.ContractPledgeService;
import top.infopub.mgr.cap.vo.ContractPledgeVo;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.mgr.mkt.dao.ProjectAttachmentDao;
import top.infopub.mgr.mkt.service.SetupProService;
import top.infopub.model.cap.*;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ContractPledgeServiceImpl extends GenericServiceImpl<ContractPledge, String> implements ContractPledgeService {

    @Autowired
    private ContractPledgeDao contractPledgeDao;
    @Autowired
    private ContractPledgeDetailDao contractPledgeDetailDao;
    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;
    @Autowired
    private SetupProService setupProService;
    @Autowired
    private OAFlowService oaFlowService;
    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private ContractGuarantyDao contractGuarantyDao;

    @Autowired
    private CapProcessManageService capProcessManageService;

    @Override
    public Page<ContractPledgeDomain> selectByDomainWhere(Page<ContractPledgeDomain> page, ContractPledgeVo contractPledgeVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<ContractPledgeDomain>)contractPledgeDao.selectByDomainWhere(contractPledgeVo);
    }

    @Override
    public GenericDao<ContractPledge, String> getDao() {
        return contractPledgeDao;
    }

    @Override
    public ContractPledgeJsonVo queryDetailById(String id) {
        String codes=codeGeneratorConfigService.generatorCode("cap_contract_pledge");
        ContractPledgeJsonVo jsonVo = new ContractPledgeJsonVo();
        //判断id是否存在，存在就显示项目下拉框，共用的一个项目名称下拉框
        if(StringUtils.isEmpty(id)){
           List<FinancingName> financingNames= contractGuarantyDao.queryListFinancingName();
           for(FinancingName finacingName:financingNames){
               //所需要的codes
              finacingName.setCodes(codes);
//             List<ContractGuaranty> institutions=  contractGuarantyDao.selectInstitutions(finacingName.getProCode());
//             jsonVo.setInstitutions(institutions);
           }
           jsonVo.setFinancingNames(financingNames);
        }else{
            //存在就修改
            /*融资基本信息*/
            ContractPledgeDto dto = contractPledgeDao.queryDetailById(id);
            jsonVo.setInfo(dto);
            /*担保单位信息*/
            List<ContractPledgeDetail> details = contractPledgeDetailDao.queryListByContractPleId(dto.getId());
            jsonVo.setDetails(details);
            for(ContractPledgeDetail detail:details) {
                //查询金融机构下拉框
                List<ContractGuaranty> institutions = contractGuarantyDao.selectInstitutions(dto.getProCode());
                jsonVo.setInstitutions(institutions);
            }
            /*附件信息表*/
            List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(dto.getProCode(), ProjectFileTypeEnum.FILE_TYPE50.getCode(), null);
            jsonVo.setFileAtt(setupProService.fileAttaListToArray(projectAttaList));
        }

        /*担保单位公司（下拉框）*/
        List<GuaranteeName> pledgeComp = contractPledgeDetailDao.queryGuaranteeName();
        jsonVo.setPledgeComp(pledgeComp);
        return jsonVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RspVo edit(ContractPledgeDto contractPledgeDto, List<ContractPledgeDetail> detailList, List<ProjectAttachment> attachmentList, Integer submitType, AuthorizationVO vo) {
        String codes=codeGeneratorConfigService.generatorCode("cap_contract_pledge");
        ContractPledge contractPledge=new ContractPledge();
        BeanUtils.copyProperties(contractPledgeDto,contractPledge);
        if(StringUtils.isNotEmpty(contractPledgeDto.getId())){
            //校验数据是否存在
            ContractPledge tmpPi = contractPledgeDao.selectByPrimaryKey(contractPledgeDto.getId());
            if (tmpPi == null) return RspVo.getFailureResponse(400, "质押合同数据不存在");
            //判断审批状态
            if (org.apache.commons.lang.StringUtils.isNotBlank(tmpPi.getProcessStatus())
                    && (org.apache.commons.lang.StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), tmpPi.getProcessStatus())
                    || org.apache.commons.lang.StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), tmpPi.getProcessStatus()))) {
                return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
            }
            contractPledge.setUptBy(vo.getId());
            contractPledge.setUptTime(new Date());
            //更新主表信息
            contractPledgeDao.updateByIdSelective(contractPledge);
        }else{
            //新增主表信息
            contractPledge.setCodes(codes);
            contractPledge.setAddBy(vo.getId());
            contractPledge.setAddTime(new Date());
            contractPledge.setProcessStatus("0");
            contractPledgeDao.insertSelective(contractPledge);
        }


        //更新子表数据
        contractPledgeDetailDao.deleteByPrimaryKey(contractPledge.getId());
        if (detailList != null && detailList.size() > 0) {
            for (ContractPledgeDetail pid : detailList) {

                pid.setCodes(codes);
                pid.setProCode(contractPledge.getProCode());
                pid.setAddBy(vo.getCode());
                pid.setAddTime(new Date());
                pid.setContractPledgeId(contractPledge.getId());
            }
            contractPledgeDetailDao.insertByBatch(detailList);

        }

        //更新附件信息
        projectAttachmentDao.deleteByWhere(contractPledge.getProCode(), ProjectFileTypeEnum.FILE_TYPE50.getCode(), null);
        if (attachmentList != null && attachmentList.size() > 0) {
            projectAttachmentDao.insertBatch(attachmentList);
        }
        if (submitType == 1) {
            if (org.apache.commons.lang.StringUtils.isNotBlank(contractPledge.getOaId())) {
                oaFlowService.finishOA(contractPledge.getOaId());
            }

            //由于担保单位和公司数据过多
            ContractPledgeJsonVo jsonVo=queryDetailById(contractPledge.getId());
            List<GuaranteeName> compNames = jsonVo.getPledgeComp();
            List<ContractPledgeDetail> infos = jsonVo.getDetails();
            if (compNames != null && compNames.size() > 0 && infos != null && infos.size() > 0) {
                List<GuaranteeName> tmpList = new ArrayList<>();
                for (ContractPledgeDetail info : infos) {
                    if (info == null) continue;
                    for (GuaranteeName gn : compNames) {
                        if (gn == null) continue;
                        if (StringUtils.equals(gn.getId(), info.getPledgeComp())) {
                            tmpList.add(gn);
                            break;
                        }
                    }
                }
                jsonVo.setPledgeComp(tmpList);
            } else {
                jsonVo.setPledgeComp(null);
            }
            String detailJson= JSON.toJSONString(jsonVo);


            capProcessManageService.sendProcess(CapProcessDetailTypeEnum.PRO_NODE_TYPE11, detailJson, contractPledge.getId(), contractPledge.getProCode(), vo);
        }
        return RspVo.getSuccessResponse();
    }


}
